var db;

function dbInit(gid) {
  try {
      if (window.openDatabase) {
          db = openDatabase("liveBoard", "1.0", "liveBoard", 200000);
          if (!db)
              alert("Failed to open the database on disk.  This is probably because the version was bad or there is not enough space left in this domain's quota");
      }
      else {
          alert("Couldn't open the database.  Please try with a WebKit nightly with this feature enabled");
      }
  }
  catch(err) { }

  $( "#loaddialog" ).dialog({autoOpen: false});
  $("#load_btn").bind('click', showLoad);

  if(db) {
    LB.DB.createDB(gid);
    LB.DB.loadDB(gid);
  }
  if(settings.autosave === 0) {
    $("#dbmessage").html("Autosave disabled");
  }
}


function showSave() {
    if(User.userLogin == 0 || User.userAuth == 0) {
        $("#logindialog").dialog("open");
        return;
    }

    $("#savemsg").html("This drawing will be saved on the remote server. Please choose a filename to save as <br><br>");
    $("#saveform").show();
    $("#savedialog").dialog("option", "buttons",
        {
          "Save": function() { save(); saveRemoteDB(); },
          "Cancel": function() { $(this).dialog("close"); }
        }
    );
    $("#savedialog").dialog("open");
}

function saveSuccess() {
    $("#savemsg").html("The drawing was successfully saved on the remote server.<br><br>");
    $("#saveform").hide();
    $("#savedialog").dialog("option", "buttons",
        {
          "Ok": function() { $(this).dialog("close"); }
        }
    );
}

function showLoad() {
    if(User.userLogin == 0 || User.userAuth == 0) {
        $("#logindialog").dialog("open");
        return;
    }

    loadRemoteDB();
    $("#loadfilelist").html("");
    $("#loadmsg").html("Loading ... ");
    $("#loaddialog").dialog("option", "buttons",
        {
          "Load": function() { load(); },
          "Cancel": function() { $(this).dialog("close"); }
        }
    );
    $("#loaddialog").dialog("open");
}


function load() {
    $.ajax({
        url: "/loadfile?name=" + $("#filelist").val(),
        cache: false,
        dataType: "json",
        success: function(obj) {
            var i = 0;
            var str = "";
            if(obj.msg === "Success") {
                var tmp = JSON.parse(obj.data[0]);
                bboxjson = tmp.bboxjson;
                g_ObjsJson = tmp.g_ObjsJson;
                delDB(0);
                LB.Canvas.restore();
                //sync the other users with the loaded file
                syncUser();
            }
            else {
                $("#loadmsg").html("");
                $("#loadfilelist").html("Could not load remote DB");
            }
        },
        error: function(error) {
            alert("remote load fail " + error);
        }
    });
    $("#loaddialog").dialog("close");
}


//Create the DB
LB.DB.createDB = function(gid) {
  db.transaction(function(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS liveBoard(id REAL UNIQUE, timestamp REAL, name TEXT, email TEXT, boxes TEXT, drawobjs TEXT, numPages REAL, currentPage REAL)', [],
       function(tx, rs) { 
         writeDebug("createDB success liveBoard: " + rs, 4); 
       },
       function(tx, err) { 
         writeDebug("createDB fail liveBoard: " + err.message, 3); 
       }
    );

    tx.executeSql('CREATE TABLE IF NOT EXISTS Book(id REAL UNIQUE, timestamp REAL, pagename TEXT, drawobjs TEXT)', [],
       function(tx, rs) { 
         writeDebug("createDB success Book : " + rs, 4); 
       },
       function(tx, err) { 
         writeDebug("createDB fail Book: " + err.message, 3); 
       }
    );
  });

  db.transaction(function(tx) {
    tx.executeSql('INSERT INTO liveBoard(id, timestamp, name, email, boxes, drawobjs, numPages, currentPage) VALUES (?,?,?,?,?,?,?,?)', [gid, 0, "", "", "", "", 0, 0],
       function(tx, rs) { },
       function(tx, err) { 
         writeDebug("insert fail liveBoard: " + err.message, 3); 
       }
    );
  });

  /*
  db.transaction(function(tx) {
    tx.executeSql('INSERT INTO Book(id, timestamp, pagename, drawobjs) VALUES (?,?,?,?)', [0, 0, "", ""],
       function(tx, rs) { },
       function(tx, err) { 
         writeDebug("insert fail Book: " + err.message, 3); 
       }
    );
  });
  */
}

LB.DB.loadPage = function(pagenum) {
  //get the page with the id above
  if(db) {
    db.transaction( function(tx) {
      tx.executeSql('SELECT * FROM Book WHERE id = ?', [pagenum],
        function(tx, rs) {
          if(rs.rows.length === 1) {
              var row = rs.rows.item(0);
              LB.Book.loadPage(row['drawobjs'], pagenum);
          }
        }
      );
    });
  }
}

LB.DB.loadDB = function(id) {
  db.transaction( function(tx) {
    tx.executeSql('SELECT * FROM liveBoard WHERE id = ?', [gid],
      function(tx, rs) {
        if(rs.rows.length === 1) {
          var row = rs.rows.item(0);
          //LB.Book.numPages = row['numPages'];
          LB.Book.currentPage = row['currentPage'];
          for(var i=0; i<=row['numPages']-1; i++) {
            /*
            var page = new Page();
            LB.Book.pages.push(page);
            */
            LB.Book.newPage();
            LB.DB.loadPage(i);
          }
          if(LB.Book.numPages > 1) {
            LB.Book.gotoPage(LB.Book.currentPage);
          }
        }
      }
    );
  });
}

function saveRemoteDB() {

    var obj = new Object();
    var name = "";
    obj['g_ObjsJson'] = g_ObjsJson;
    obj['bboxjson'] = bboxjson;
    obj['gid'] = gid;
    if($("#savename").val() === "") {
        obj['name'] = "Unknown"
    }
    else {
        obj['name'] = $("#savename").val();
    }

    $.ajax({
        type: "POST",
        url: "/save",
        cache: false,
        data: JSON.stringify(obj),
        success: saveSuccess,
        error: function(error) {
            alert("remote save fail " + error);
        }
    });
}


function loadRemoteDB() {
    $.ajax({
        url: "/load",
        cache: false,
        dataType: "json",
        success: function(obj) {
            var i = 0;
            var str = "";
            $("#loadfilelist").html("");
            if(obj.msg === "Success") {
                $("#loadmsg").html("Please select a file to load. Use two-finger scroll.<br><br>");
                str = '<select id="filelist" multiple="true" size="10" class="ui-widget-content">';
                for(i=0; i<obj.data.length; i++) {
                    str += '<option value=' + obj.data[i].name + '>' + 
                obj.data[i].date + ' ' + obj.data[i].name + '</option>';
                } 
                str += '</select>';
                $("#loadfilelist").append(str);
            }
            else {
                $("#loadmsg").html("");
                $("#loadfilelist").html("Could not load remote DB");
            }
        },
        error: function(error) {
            alert("remote load fail " + error);
        }
    });
}


LB.DB.savePage = function(currPage, name, data, numPages) {
  var time = new Date();
  var timestamp = time.getTime();
  if(db) {
    db.transaction(function(tx) {
      tx.executeSql('REPLACE INTO Book(id, timestamp, pagename, drawobjs) VALUES (?,?,?,?)', [currPage, timestamp, name, data],
         function(tx, rs) {
           LB.UI.alert("Successfully save the drawing with name: " + name);
         },
         function(tx, err) {
           LB.UI.alert("Failed to save in local DB");
         }
      );
    });
  }
  LB.DB.saveDB(currPage, numPages);
}

LB.DB.saveDB = function(currentPage, numPages) {
  var time = new Date();
  var timestamp = time.getTime();
  var h = time.getHours();
  var m = time.getMinutes();
  var s = time.getSeconds();
  
  if(db) {
    db.transaction(function(tx) {
      tx.executeSql('UPDATE liveBoard SET timestamp = ?, name = ?, email = ?, boxes = ?, drawobjs = ?, numPages = ?, id = ?, currentPage = ?', [timestamp, username, "", bboxjson, g_ObjsJson, numPages, 0, currentPage],
         function(tx, rs){
           //LB.UI.alert("Autosaved: "+h+":"+m+":"+ s);
         },
         function(tx, err){
           LB.UI.alert("Failed to save in local DB");
         }
      );
    });

  }
}

//delete the rows and the entire Table to start fresh on reset
//or on loading a new file
function delDB(gid) {
  if(db) {
    db.transaction(function(tx) {
      tx.executeSql('DROP TABLE liveBoard', [], 
        function(tx, rs){
          LB.UI.message("Successfully deleted local DB");
          LB.DB.createDB(gid);
        },
        function(tx, err){
           $("#dbmessage").html("Failed to delete local DB: " + err);
        }
      );
    });
  }
}
